package com.ruoyi.system.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;

import java.io.FileOutputStream;
import java.io.InputStream;

public class OSSImageDownload {
    // 复用上传流程中的OSS参数（ENDPOINT、ACCESS_KEY等）
    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tBeagSeMrJje1pf7LCj";
    private static final String ACCESS_KEY_SECRET = "X85WnvwbcFm3hPumcwh1GWxgXnBREa";
    private static final String BUCKET_NAME = "aoba-pic";

    public static void downloadImage(String ossKey, String localSavePath) {
        // 1. 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 2. 获取OSS中的图片对象
            OSSObject ossObject = ossClient.getObject(BUCKET_NAME, ossKey);

            // 3. 读取图片输入流
            InputStream inputStream = ossObject.getObjectContent();

            // 4. 将流写入本地文件
            FileOutputStream outputStream = new FileOutputStream(localSavePath);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            System.out.println("下载成功，保存路径：" + localSavePath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    // 测试下载
    public static void main(String[] args) {
        // OSS中图片的存储路径
        String ossKey = "images/test.jpg";
        // 本地保存路径（如：/Users/test/download.jpg）
        String localSavePath = "localSavePath";
        downloadImage(ossKey, localSavePath);
    }
}
